package com.example.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.yijiu.trb.App;

public class ImageUtils
{
	public static final String BASE_IMG_URL = App.IMAGE_URL;
	
	public static void setImage(String url, ImageView imgView)
	{
		ImgLoader loader = new ImgLoader(BASE_IMG_URL + url, imgView);
		loader.execute();
	}
	
	public static class ImgLoader extends AsyncTask<Void, Bitmap, Void>
	{
		private String url;
		private ImageView imgView;
		
		public ImgLoader(String url, ImageView imgView)
		{
			this.url = url;
			this.imgView = imgView;
		}
		@Override
		protected Void doInBackground(Void... arg0)
		{
			URL myFileUrl = null;
			Bitmap bitmap = null;
			try
			{
				myFileUrl = new URL(url);
			}
			catch (MalformedURLException e)
			{
				e.printStackTrace();
			}
			try
			{
				HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
				conn.setDoInput(true);
				conn.connect();
				InputStream is = conn.getInputStream();
				// 解决加载图片 内存溢出的问题
				// Options 只保存图片尺寸大小，不保存图片到内存
				BitmapFactory.Options opts = new BitmapFactory.Options();
				// 缩放的比例，缩放是很难按准备的比例进行缩放的，其值表明缩放的倍数，SDK中建议其值是2的指数值,值越大会导致图片不清晰
				opts.inSampleSize = 2;
				opts.inPurgeable = true;
				opts.inInputShareable = true;
				opts.inJustDecodeBounds = false;
				bitmap = BitmapFactory.decodeStream(is, null, opts);
				this.publishProgress(bitmap);
				is.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(Bitmap... values)
		{
			super.onProgressUpdate(values);
			if (values[0] != null)
			{
				imgView.setImageBitmap(values[0]);
			}
		}
	}
}
